<template>
  <div class="shop-root">
    <el-card class="shop-card">
      <div class="shop-header">
        <h2>商家管理</h2>
        <el-input
          v-model="search"
          placeholder="搜索商家名称"
          clearable
          class="shop-search"
          @input="filterShops"
        />
        <el-button
          type="primary"
          @click="openAddDialog"
        >
          新增商家
        </el-button>
        <el-button
          type="danger"
          :disabled="!multipleSelection.length"
          class="shop-btn"
          @click="batchDelete"
        >
          批量删除
        </el-button>
      </div>
      <el-table
        :data="filteredShops"
        style="width: 100%; margin-top: 16px;"
        border
        @row-click="editShopDialog"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="48"
        />
        <el-table-column
          label="Logo"
          width="80"
        >
          <template #default="scope">
            <el-avatar
              :src="scope.row.logo"
              size="large"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          label="商家名称"
        />
        <el-table-column
          prop="desc"
          label="简介"
        />
        <el-table-column
          label="状态"
          width="100"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-text="营业中"
              inactive-text="休息中"
              active-value="营业中"
              inactive-value="休息中"
              @change="toggleStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click.stop="editShopDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click.stop="deleteShop(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="editMode ? '编辑商家' : '新增商家'"
      width="420px"
      class="shop-dialog"
      :close-on-click-modal="false"
    >
      <el-card class="shop-detail-card">
        <el-form
          ref="shopFormRef"
          :model="editShop"
          label-width="80px"
          label-position="top"
          :rules="rules"
        >
          <el-form-item
            label="商家名称"
            prop="name"
          >
            <el-input v-model="editShop.name" />
          </el-form-item>
          <el-form-item
            label="简介"
            prop="desc"
          >
            <el-input v-model="editShop.desc" />
          </el-form-item>
          <el-form-item
            label="Logo链接"
            prop="logo"
          >
            <el-input
              v-model="editShop.logo"
              placeholder="可粘贴图片链接"
            />
          </el-form-item>
          <el-form-item label="Logo上传">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              action="https://jsonplaceholder.typicode.com/posts/"
            >
              <img
                v-if="editShop.logo"
                :src="editShop.logo"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              />
            </el-upload>
          </el-form-item>
          <el-form-item
            label="状态"
            prop="status"
          >
            <el-switch
              v-model="editShop.status"
              active-text="营业中"
              inactive-text="休息中"
              active-value="营业中"
              inactive-value="休息中"
            />
          </el-form-item>
        </el-form>
      </el-card>
      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="saveShop"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

interface Shop {
  id: number
  name: string
  desc: string
  logo: string
  status: string
}

const shops = ref<Shop[]>([
  { id: 1, name: '食堂一号店', desc: '主营快餐、盖饭、饮品', logo: 'https://img1.imgtp.com/2023/07/21/1.jpg', status: '营业中' },
  { id: 2, name: '校园奶茶', desc: '各类奶茶、果饮、甜品', logo: 'https://img1.imgtp.com/2023/07/21/2.jpg', status: '休息中' },
  { id: 3, name: '炸鸡汉堡', desc: '炸鸡、汉堡、薯条', logo: 'https://img1.imgtp.com/2023/07/21/3.jpg', status: '营业中' }
])

const search = ref('')
const filteredShops = ref<Shop[]>([...shops.value])

const filterShops = () => {
  filteredShops.value = shops.value.filter(shop =>
    !search.value || shop.name.includes(search.value)
  )
}

// 多选相关
const multipleSelection = ref<Shop[]>([])
const handleSelectionChange = (val: Shop[]) => {
  multipleSelection.value = val
}
const batchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的商家吗？', '提示', { type: 'warning' })
    .then(() => {
      shops.value = shops.value.filter(shop => !multipleSelection.value.includes(shop))
      filterShops()
      ElMessage.success('批量删除成功')
    })
}

// 行操作相关
const dialogVisible = ref(false)
const editShop = ref<Shop>({ id: 0, name: '', desc: '', logo: '', status: '营业中' })
const editMode = ref(false)
const shopFormRef = ref()

const rules = reactive({
  name: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
  desc: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  logo: [{ required: true, message: '请上传Logo', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

const openAddDialog = () => {
  editShop.value = { id: 0, name: '', desc: '', logo: '', status: '营业中' }
  editMode.value = false
  dialogVisible.value = true
}
const editShopDialog = (row: Shop) => {
  editShop.value = { ...row }
  editMode.value = true
  dialogVisible.value = true
}
const saveShop = () => {
  shopFormRef.value.validate((valid: boolean) => {
    if (!valid) return
    if (editMode.value) {
      const idx = shops.value.findIndex(s => s.id === editShop.value.id)
      if (idx !== -1) shops.value[idx] = { ...editShop.value }
      ElMessage.success('商家信息已更新')
    } else {
      editShop.value.id = Date.now()
      shops.value.push({ ...editShop.value })
      ElMessage.success('新增商家成功')
    }
    filterShops()
    dialogVisible.value = false
  })
}
const deleteShop = (row: Shop) => {
  ElMessageBox.confirm('确定要删除该商家吗？', '提示', { type: 'warning' })
    .then(() => {
      shops.value = shops.value.filter(shop => shop.id !== row.id)
      filterShops()
      ElMessage.success('删除成功')
    })
}
const toggleStatus = (row: Shop) => {
  row.status = row.status === '营业中' ? '休息中' : '营业中'
  ElMessage.info('状态已切换为：' + row.status)
}
// 上传Logo相关（模拟，支持本地预览）
const handleAvatarSuccess = (response: any, file: any) => {
  if (file.url) {
    editShop.value.logo = file.url
  } else if (file.thumbUrl) {
    editShop.value.logo = file.thumbUrl
  } else if (file.raw) {
    const reader = new FileReader()
    reader.onload = e => {
      editShop.value.logo = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
  ElMessage.success('上传成功（模拟）')
}
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) ElMessage.error('只能上传 JPG/PNG 图片!')
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB!')
  return isJPG && isLt2M
}
</script>

<style scoped>
.shop-root {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px 0 40px 0;
}
.shop-card {
  border-radius: 14px;
  box-shadow: 0 2px 12px #e6e6e6;
  padding: 24px 18px 32px 18px;
}
.shop-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 8px;
}
.shop-search {
  width: 220px;
}
.shop-dialog .el-dialog__body {
  padding: 0 24px 24px 24px;
}
.shop-detail-card {
  border-radius: 10px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 18px 12px 12px 12px;
  background: #f9fbff;
}
</style> 